<template>
    <div class="container">
        <el-tag>入住登记信息管理界面</el-tag><br>
        <el-form :inline="true" class="query-form">
            <el-form-item label="房间号码 / 住户姓名">
                <el-input v-model="queryText" placeholder="请输入查询关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery" plain>查询</el-button>
            </el-form-item>
        </el-form>

        <el-button type="primary" class="add-button" @click="showAddDialog">
            新增
        </el-button>

        <el-table :data="filteredData" border class="center-table">
            <!-- 表格列 -->
            <el-table-column label="编号" width="60">
                <template slot-scope="scope">
                    <!-- 使用 v-for 指令和索引显示编号 -->
                    <span :index="scope.$index + 1">{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="roomnumber" label="房间号码" width="80"></el-table-column>
            <el-table-column prop="roomtype" label="房间类型"></el-table-column>
            <el-table-column prop="price" label="价格" width="80"></el-table-column>
            <el-table-column prop="fullname" label="住户姓名"></el-table-column>
            <el-table-column prop="userid" label="身份证号码"></el-table-column>
            <el-table-column prop="phone" label="手机号码" width="120"></el-table-column>
            <el-table-column prop="checkindate" label="入住时间"></el-table-column>
            <el-table-column prop="days" label="入住天数" width="80"></el-table-column>
            <el-table-column prop="deposit" label="预收押金" width="80"></el-table-column>
            <el-table-column prop="sumprice" label="合计金额" width="80"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>

            <!-- 编辑按钮列 -->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" plain size="small" @click="showEditDialog(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" plain size="small" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination style="margin-top: 20px;" :current-page="currentPage" :page-size="pageSize" :total="totalRows"
            @current-change="handlePageChange"></el-pagination>

        <!-- 新增弹窗 -->
        <el-dialog title="新增入住登记信息" :visible="isAddDialogVisible" :scrollable="false" @close="resetAddDialog" width="800px">
            <el-form ref="addRegistration" :model="addRegistration" label-width="80px" style="padding: 0px 50px;">
                <el-form-item label="房间号码" required>
                    <el-select v-model="addRegistration.roomnumber" style="width: 100%;">
                        <el-option v-for="room in roomList" :key="room.roomnumber"
                            :label="room.roomnumber + '（== ' + room.roomtype + ' == ' + room.price + '元 == 房间空闲 ==）'"
                            :value="room.roomnumber">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="房间类型" required>
                    <el-input v-model="addRegistration.roomtype" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="房间价格" required>
                    <el-input v-model="addRegistration.price" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="住户姓名" required>
                    <el-input v-model="addRegistration.fullname"></el-input>
                </el-form-item>
                <el-form-item label="身份证" required>
                    <el-input v-model="addRegistration.userid" maxlength="18"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" required>
                    <el-input v-model="addRegistration.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="入住时间" required>
                    <el-date-picker v-model="addRegistration.checkindate" type="datetime" placeholder="选择日期时间"
                        style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="入住天数" required>
                    <el-input v-model="addRegistration.days" type="number"></el-input>
                </el-form-item>
                <el-form-item label="预收押金" required>
                    <el-input v-model="addRegistration.deposit" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="合计金额" required>
                    <el-input v-model="addRegistration.sumprice" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addRegistration.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="resetAddDialog">取消</el-button>
                <el-button type="primary" @click="handleAdd">提交</el-button>
            </div>
        </el-dialog>

        <!-- 编辑弹窗 -->
        <el-dialog title="新增入住登记信息" :visible="isEditDialogVisible" :scrollable="false" @close="resetEditDialog"
            width="800px">
            <el-form ref="editRegistration" :model="editRegistration" label-width="80px" style="padding: 0px 50px;">
                <el-form-item label="房间号码" required>
                    <el-select v-model="editRegistration.roomnumber" style="width: 100%;" :disabled="true">
                        <el-option v-for="room in roomList" :key="room.roomnumber"
                            :label="room.roomnumber + '（' + room.roomtype + ' ￥' + room.price + '）'"
                            :value="room.roomnumber">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="房间类型" required>
                    <el-input v-model="editRegistration.roomtype" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="房间价格" required>
                    <el-input v-model="editRegistration.price" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="住户姓名" required>
                    <el-input v-model="editRegistration.fullname"></el-input>
                </el-form-item>
                <el-form-item label="身份证" required>
                    <el-input v-model="editRegistration.userid"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" required>
                    <el-input v-model="editRegistration.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="入住时间" required>
                    <el-date-picker v-model="editRegistration.checkindate" type="datetime" placeholder="选择日期时间"
                        style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="入住天数" required>
                    <el-input v-model="editRegistration.days" type="number"></el-input>
                </el-form-item>
                <el-form-item label="预收押金" required>
                    <el-input v-model="editRegistration.deposit" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="合计金额" required>
                    <el-input v-model="editRegistration.sumprice" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editRegistration.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="resetEditDialog">取消</el-button>
                <el-button type="primary" @click="handleEdit">提交</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            queryText: '', // 查询关键字
            rooms: [],
            tableData: [], // 所有数据
            filteredData: [], // 过滤后的数据
            isAddDialogVisible: false, // 新增弹窗是否显示
            isEditDialogVisible: false, // 编辑弹窗是否显示
            addRegistration: {
                roomnumber: '',
                roomtype: '',
                price: '',
                fullname: '',
                userid: '',
                phone: '',
                checkindate: '',
                days: '1',
                deposit: '500',
                sumprice: '',
                remark: '',
            },
            editRegistration: { // 编辑表单数据
                roomnumber: '',
                roomtype: '',
                price: '',
                fullname: '',
                userid: '',
                phone: '',
                checkindate: '',
                days: '',
                deposit: '',
                sumprice: '',
                remark: '',
            },
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的行数
            totalRows: 0, // 总行数
        };
    },
    mounted() {
        if (!localStorage.getItem('users')) {
            this.$router.push("/");
            this.$message({
                message: '用户未登录！非法操作！',
                type: 'error'
            });
        }
        //获取房间信息
        axios.get('http://localhost:8888/roomstatus/get')
            .then(response => {
                this.rooms = response.data;
            }).catch(error => {
                console.error(error);
            });

        this.getData(); // 在页面加载时触发获取数据的方法

    },

    computed: {
        //显示空闲房间
        roomList: function () {
            return this.rooms.filter(room => room.status === '空闲');
        },
        //根据房间号码计算
        selectedRoom: function () {
            return this.rooms.find(room => room.roomnumber === this.addRegistration.roomnumber);
        },
    },
    watch: {
        'addRegistration.roomnumber': function (newRoomNumber) {
            const selectedRoom = this.rooms.find(room => room.roomnumber === newRoomNumber);
            if (selectedRoom) {
                this.addRegistration.roomtype = selectedRoom.roomtype;
                this.addRegistration.price = selectedRoom.price;
                this.updateSumPrice();
            }
        },
        'addRegistration.days': function (newDays) {
            this.updateSumPrice();
        }
    },

    methods: {
        getData() {
            // 发送请求获取数据，例如使用axios或其他方式
            axios.get('http://localhost:8888/registrationinfo/get')
                .then(response => {
                    // 处理请求成功情况
                    console.log('获取数据成功');
                    this.tableData = response.data; // 将获取到的数据赋值给tableData
                    this.totalRows = this.tableData.length; // 设置总行数
                    this.filteredData = this.tableData.slice(
                        (this.currentPage - 1) * this.pageSize,
                        this.currentPage * this.pageSize
                    ); // 初始化filteredData，根据当前页码和每页显示的行数进行切片
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },
        updateSumPrice: function () {
            const selectedRoom = this.selectedRoom;
            if (selectedRoom) {
                const totalPrice = selectedRoom.price * this.addRegistration.days;
                this.addRegistration.sumprice = parseInt(totalPrice) + parseInt(this.addRegistration.deposit);
            }
        },
        handleQuery() {
            if (this.queryText === '') {
                this.getData();
            }
            this.filteredData = this.tableData.filter(item => {
                return (
                    item.roomnumber.toString().includes(this.queryText) ||
                    item.fullname.includes(this.queryText)
                );
            });
        },

        showAddDialog() {
            this.isAddDialogVisible = true; // 显示新增弹窗
        },

        resetAddDialog() {
            this.isAddDialogVisible = false;
            this.addRegistration = { days: '1', deposit:'500'}
        },

        handleAdd() {

            if (
                !this.addRegistration.roomnumber ||
                !this.addRegistration.roomtype ||
                !this.addRegistration.price ||
                !this.addRegistration.fullname ||
                !this.addRegistration.userid ||
                !this.addRegistration.phone ||
                !this.addRegistration.checkindate ||
                !this.addRegistration.days ||
                !this.addRegistration.deposit ||
                !this.addRegistration.sumprice
            ) {
                this.$message({
                    type: 'error',
                    message: '必填项不能为空！'
                });
                return false;
            }

            if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(this.addRegistration.userid)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的身份证号码！'
                });
                return false;
            }

            if (!/^1[3456789]\d{9}$/.test(this.addRegistration.phone)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的手机号！'
                });
                return false;
            }
            // 转换时间格式
            const date = this.addRegistration.checkindate;
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            this.addRegistration.checkindate = formattedDate;

            axios
                .post('http://localhost:8888/registrationinfo/add', this.addRegistration)
                .then(response => {
                    // 处理新增成功情况
                    this.$message({
                        type: 'success',
                        message: '新增成功！'
                    });

                    this.getData();
                    this.isAddDialogVisible = false;
                    // 刷新数据

                    this.handleQuery();
                    // 关闭弹窗
                    this.resetAddDialog();
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });

            /* 登记入住产生订单信息 */
            const newOrder = {
                ordernumber: this.generateUUID(),
                roomnumber: this.addRegistration.roomnumber,
                fullname: this.addRegistration.fullname,
                checkindate: this.addRegistration.checkindate,
                sumprice: this.addRegistration.price,
                paystatus: '已支付',
                remark: this.addRegistration.remark,
            }

            axios
                .post('http://localhost:8888/order/add', newOrder)
                .then(response => {
                    console.log("order add success");
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });

            /* 更改房间状态 */
            const roomStatus = {
                roomnumber: this.addRegistration.roomnumber,
                fullname: this.addRegistration.fullname,
                phone: this.addRegistration.phone,
                status: '入住',
                remark: this.addRegistration.remark
            };
            axios
                .put(`http://localhost:8888/roomstatus/status/${this.addRegistration.roomnumber}`, roomStatus)
                .then(response => {
                    console.log("roomstatus update success");
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });

        },

        /* 生成uuid */
        generateUUID() {
            let d = new Date().getTime();
            const uuid = 'xxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                const r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        },

        showEditDialog(row) {
            this.editRegistration = Object.assign({}, row); // 将当前行的数据复制到编辑表单
            this.isEditDialogVisible = true; // 显示编辑弹窗
        },

        resetEditDialog() {
            this.isEditDialogVisible = false;
            this.$refs.editRegistration.resetFields(); // 重置编辑表单
        },

        handleEdit() {
            if (
                !this.editRegistration.roomnumber ||
                !this.editRegistration.roomtype ||
                !this.editRegistration.price ||
                !this.editRegistration.fullname ||
                !this.editRegistration.userid ||
                !this.editRegistration.phone ||
                !this.editRegistration.checkindate ||
                !this.editRegistration.days ||
                !this.editRegistration.deposit ||
                !this.editRegistration.sumprice
            ) {
                this.$message({
                    type: 'error',
                    message: '必填项不能为空！'
                });
                return false;
            }

            if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(this.editRegistration.userid)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的身份证号码！'
                });
                return false;
            }

            if (!/^1[3456789]\d{9}$/.test(this.editRegistration.phone)) {
                this.$message({
                    type: 'error',
                    message: '请输入正确的手机号！'
                });
                return false;
            }

            // 转换时间格式
            const date = this.editRegistration.checkindate;
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            this.editRegistration.checkindate = formattedDate;


            axios
                .put(`http://localhost:8888/registrationinfo/update/${this.editRegistration.id}`, this.editRegistration)
                .then(response => {
                    this.$message({
                        type: 'success',
                        message: '编辑成功！'
                    });
                    this.getData();
                    this.handleQuery();
                    // 关闭弹窗
                    this.resetEditDialog();
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },
        handleDelete(row) {
            // 弹窗确认是否删除
            this.$confirm('确定删除该房间吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    // 发送删除请求
                    axios.delete(`http://localhost:8888/registrationinfo/delete/${row.id}`)
                        .then(response => {
                            this.$message({
                                type: 'success',
                                message: '删除成功！'
                            });
                            this.getData();
                        })
                        .catch(error => {
                            // 处理请求错误
                            console.error(error);
                        });
                })
                .catch(() => {
                    // 取消删除操作
                    console.log('取消删除');
                });
        },
        handlePageChange(currentPage) {
            this.currentPage = currentPage; // 更新当前页码
            this.filteredData = this.tableData.slice(
                (this.currentPage - 1) * this.pageSize,
                this.currentPage * this.pageSize
            ); // 根据新的页码进行数据切片
        },

    }
};
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.add-button {
    margin-bottom: 10px;
}

.query-form .el-form-item {
    margin-right: 10px;
}

.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.center-table .cell {
    text-align: center;
}
</style>
